package com.zhugang.week04;

/**
 * @program algorithms
 * @description: bubbleSort
 * @author: chanzhugang
 * @create: 2022/06/25 12:00
 */
public class BubbleSort2 {

    public static void main(String[] args) {
        BubbleSort2 bubbleSort2 = new BubbleSort2();
        int[] a = new int[]{3, 4, 5, 1, 2, 0};
        bubbleSort2.bubbleSort(a, a.length);
        for (int i : a) {
            System.out.println(i);
        }
    }

    /**
     * 冒泡排序
     *
     * @param a
     * @param n
     */
    public void bubbleSort(int[] a, int n) {
        // 比较相邻元素大小，交换位置
        for (int i = 0; i < n; i++) {
            boolean flag = false;
            for (int j = 0; j < n - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    swap(a, j);
                    flag = true;
                }
            }
            // 已经排好序，退出外层循环
            if (!flag) break;
        }
    }

    private void swap(int[] a, int j) {
        int temp = a[j];
        a[j] = a[j + 1];
        a[j + 1] = temp;
    }

}